<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 工具栏结构 -->
      <page-tools :show-before="true">
        <!-- 左边信息 -->
        <template v-slot:before>
          <span slot="before">共{{ page.total }}条记录</span>
        </template>
        <!-- 右边按钮 -->
        <template v-slot:after>
          <el-button size="small" type="warning" @click="$router.push('/import')">excel导入</el-button>
          <el-button size="small" type="danger" @click="exportData">excel导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表格结构 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />

          <el-table-column label="头像" align="center">
            <template v-slot="{ row }">
              <img
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>

          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column prop="formOfEmployment" label="聘用形式" :formatter="formatEmployment" sortable="" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <!-- 作用域插槽 -->
            <template slot-scope="{row}">
              {{
                row.timeOfEntry | formatDate
              }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="" />
          <el-table-column label="操作" sortable="" fixed="right" width="280px">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 放置分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height:60px">
          <el-pagination :page-size="page.size" :total="page.total" layout="prev,pager,next" @current-page="page.page" @current-change="changePage" />
        </el-row>
      </el-card>
    </div>
    <!-- sync 修饰符 是子组件去改变父组件的数据的语法塘 -->
    <add-employee :show-dialog.sync="showDialog" />
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 放置弹出角色组件 -->
    <assign-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmpolyeeList, delEmployee } from '@/api/employess'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters/index'
import AssignRole from './components/assign-role.vue'
import QrCode from 'qrcode'
export default {
  components: { AddEmployee, AssignRole },
  data() {
    return {
      loading: false, // 加载条
      list: [], // 接收数据
      page: {
        page: 1, // 当前页码
        size: 10, // 一页的条数
        total: 0// 总数
      },
      showDialog: false,
      showCodeDialog: false, // 控制二维码弹层的显示隐藏
      showRoleDialog: false, // 控制角色信息弹层组件
      userId: null // 当前点击的角色id

    }
  },
  created() {
    this.getEmpolyeeList()
  },
  methods: {
    // 获取员工数据
    async getEmpolyeeList() {
      this.loading = true
      const { rows, total } = await getEmpolyeeList(this.page)

      this.page.total = total
      this.list = rows
      this.loading = false
    },
    // 点击分页功能
    changePage(newPage) {
      this.page.page = newPage
      this.getEmpolyeeList()
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      //  要去找1对应的值
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除员工
    async deleteEmployee(id) {
      try {
        await this.$confirm('您确定删除员工吗')
        await delEmployee(id)
        this.getEmpolyeeList()// 重新获取数据
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    exportData() {
      // 做操作
      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      //
      import('@/vendor/Export2Excel').then(async excel => {
        // 获取数据，一页全部获取完成
        const { rows } = await getEmpolyeeList({ page: 1, size: this.page.total })
        // 处理数据  变成data：[[张三，13522222222]]
        const data = this.formatJson(headers, rows)
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data, // 具体数据
          filename: '导出数据',
          autoWidth: true, // 自动适应宽度
          bookType: 'xlsx',
          multiHeader, // 复杂表头
          merges // 需要合并的表头部分
        })
      })
    },
    // 该方法负责将数组转化成二维数组
    formatJson(headers, rows) {
      //  遍历数组
      // [{ username: '张三'},{},{}]  => [[’张三'],[],[]]
      return rows.map(item => {
        // 遍历表头数据
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
          // console.log(headers[key])英文的表头数据
          // console.log(item[headers[key]]) //英文表头所对应的值
        })
      })
    },
    // 点击图片生成二维码
    showQrCode(url) {
      if (url) {
        this.showCodeDialog = true
        // 数据更新了 但是我们的弹层会立刻弹出来吗？页面的渲染是异步的
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后执行
        this.$nextTick(() => {
          // 此时可以确认已经渲染了 ref 对象了
          QrCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该用户没有上传头像')
      }
    },
    // 点击角色按钮
    async  editRole(id) {
      this.userId = id
      // props 赋值 是异步的
      // await 方法是为了解决点击闪动的问题，加载完成员工角色的信息在往后面执行
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    }
  }
}
</script>

<style>

</style>
